<?php

class MenuController extends BaseClass
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $title;	//Page Title
	public $layout = 'main';
	
	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions' => array('index', 'add', 'delete', 'update', 'changeOrder'),
				'users' => $this->getAdmins(),
			),
// 			array('deny', // deny other user to perform actions
// 					'actions' => array('index', 'add', 'delete', 'update', 'changeOrder'),
// 					'users' => array('*'),
// 			),
		);
	}
	

	/**
	 * Lists all models.
	 */
	public function actionIndex(){
		$this->title = Yii::app()->name."- Menu Bar";
		$model = new Menus();
		$this->render('index', array('model'=>$model));
	}
	/**
	 * 
	 * @param navigation Id
	 * update a navigation bar
	 */
	public function actionUpdate($id) {
		if (isset($_REQUEST['id']) && !empty($_REQUEST['id'])){
			$id = $_REQUEST['id'];
		}
		$menus = Menuitems::model()->findAllByAttributes(array('menu_position'=>$id, 'parent'=>'0'), array('order'=>'sequence'));
		$pages = Cms::model()->findAllByAttributes(array('status'=>'1', 'is_datacard' => '0'), array('order'=>'id desc'));
		$model = new Menuitems();
		
		if( isset($_POST['Menuitems']) && !empty($_POST['Menuitems']) ){
			$i = 0;
			
			foreach( $_POST['Menuitems']['page_id'] as $menu ){
				$model = new Menuitems();
				
				$criteria=new CDbCriteria;
				$criteria->select='max(sequence) AS sequence';
				$row = $model->model()->find($criteria);
				$model->sequence = $row['sequence']+1;
				$model->page_id = $menu;
				$model->menu_position = $id;
				$model->parent = 0;
				$model->save();
				$i++;
			}
			$this->redirect(Yii::app()->getBaseUrl().'/admin/menu/update/id/'.$id);
		}
		$this->title = Yii::app()->name."- Add Menu";
		$this->render('add',array(
			'menus'=>$menus,
			'pages' => $pages,
			'model' => $model,
			'menuPosition' => $id,
		));
	}
	
	
	public function actionProcess(){
		$model = new Menus();
		if($_POST['pageAction'] == 'delete')
		{
			if($model->deleteByPk($_POST['contact'])) {
				Yii::app()->user->setFlash('success','Record (s) Successfully Deleted');
				$this->redirect(Yii::app()->getBaseUrl().'/admin/menu');
			}
			else {
				Yii::app()->user->setFlash('error','Record (s) not Deleted');
				$this->redirect(Yii::app()->getBaseUrl().'/admin/menu');
			}
		}
	}
	
	
	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete()
	{
		$id = ( isset($_POST['id']) && !empty($_POST['id']) ) ? $_POST['id'] : '';
		if ($id){
			if (Menuitems::model()->deleteByPk($id))
				echo 'success';
	
			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		}
	}
	
	/**
	 *  function to change the order of menu bars / navigation as per their positions
	 */
	public function actionChangeOrder(){
		if ( isset($_POST['data']) && !empty($_POST['data']) ){

			$menuPosition = $_POST['menuPosition'];
			unset($_POST['menuPosition']);
			
			$orders = json_decode($_POST['data']);
			
			$this->_updateOrder($orders);
		}
	}
	protected function _updateOrder($orders, $parent=0){
		$counter = 1;
		foreach($orders as $order){
			$items = Menuitems::model()->findByPk($order->page_id);
			$items->sequence = $counter;
			$items->parent = $parent;
			$items->update();
			if( isset($order->children) && count($order->children) > 0 ){
				$this->_updateOrder($order->children, $order->page_id);
			}
			$counter++;
		}
	} 
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Menus the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Menus::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Menus $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='menus-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
